<?php

/**
 * 公共函数
 */
defined('EMLOG_ROOT') || exit('access denied!');

function getTimePeriod()
{
  // 获取当前小时数
  $hour = date('G');

  // 判断时间段
  if ($hour >= 6 && $hour < 12) {
    return '上午';
  } elseif ($hour >= 12 && $hour < 18) {
    return '下午';
  } else {
    return '晚上';
  }
}

// 输出作者头像URL
function author_head($uid)
{
  global $CACHE;
  if (!$uid) return BLOG_URL . '/admin/views/images/avatar.svg';
  $user_cache = $CACHE->readCache('user');
  if (isset($user_cache[$uid]['photo']['src'])) {
    $head_url = BLOG_URL . $user_cache[$uid]['photo']['src'];
  } else if (isset($user_cache[$uid]['mail'])) {
    $head_url = getGravatar($user_cache[$uid]['mail']);
  } else {
    $head_url = BLOG_URL . '/admin/views/images/avatar.svg';
  }
  return $head_url;
}
// 输出作者名字
function author_name($uid)
{
  global $CACHE;
  if (!$uid) return '';
  $user_cache = $CACHE->readCache('user');
  if (!isset($user_cache[$uid])) return '该用户已注销';
  $author =  $user_cache[$uid]['name'] ? $user_cache[$uid]['name'] : '暂无昵称';
  return $author;
}
// 输出作者信息
function author_des($uid)
{
  global $CACHE;
  if (!$uid) return '';
  $user_cache = $CACHE->readCache('user');
  $des = isset($user_cache[$uid]['des']) ? $user_cache[$uid]['des']  : '该博主没有留下什么话...';
  if ($des) return $des;
}

// 文章标签
function log_tags($blogid)
{
  $tag_model = new Tag_Model();
  $tag_ids = $tag_model->getTagIdsFromBlogId($blogid);
  $tag_names = $tag_model->getNamesFromIds($tag_ids);
  if (!empty($tag_names)) {
    $tag = '';
    foreach ($tag_names as $value) {
      $tag .= "<a class=\"article-card-tag\" href=\"" . Url::tag(rawurlencode($value)) . "\"  title='标签' >" . htmlspecialchars($value) . '</a>';
    }
    echo $tag;
  }
}
// 文章点赞
function log_likes($gid)
{
  $Like_Model = new Like_Model();
  $r = $Like_Model->getList($gid);
  $links = [];
  foreach ($r as $value) {
    $likes[] = [
      'id'          => (int)$value['id'],
      'gid'         => (int)$value['gid'],
      'uid'         => (int)$value['uid'],
      'date'        => $value['date'],
      'avatar'      => $value['avatar'],
      'poster'      => $value['poster'],
    ];
  }
  return $likes;
}
// 用户是否点赞
function isLikeUser($gid, $uid)
{
  $likes =  log_likes($gid);
  foreach ($likes as $value) {
    if ($value['uid'] == $uid) return true;
  }
  return false;
}
/**
 * 文章随机图片
 * */
function roundImage()
{
  return TEMPLATE_URL . 'static/images/random/' . rand(1, 35) . '.jpg';
}
/**
 * 获取文章全部的图片
 * */
function get_log_image($content)
{
  $partnner = '!\[(.*)\]\((.+)\)!';
  preg_match_all($partnner, $content, $match);
  $imgs = [];
  $imgarr = [];
  for ($i = 0; $i < count($match[2]); $i++) {
    array_push($imgarr, explode(" ", $match[2][$i]));
  }


  for ($j = 0; $j < count($imgarr); $j++) {
    // jpg png jpeg 显示 防止 []() 
    if (preg_match("/jpg|jpeg|png/", $imgarr[$j][0])) {
      array_push($imgs, $imgarr[$j][0]);
    }
  }
  return $imgs;
}
/**
 * 获取文章所有图片
 **/
function getLogAllImages($content)
{
  // 匹配 Markdown 中的图片
  preg_match_all('/!\[.*?\]\((.*?)\)/', $content, $matches);
  $imgs = [];
  if (!empty($matches[1])) {
    foreach ($matches[1] as &$value) {
      array_push($imgs, $value);
    }
    unset($value);
    return $imgs;
  }
  // 去除 pre 防止获取其内容
  // $content = replace_html_tags(['pre'], $content);
  if (!$content) return [];

  // 匹配 HTML 中的图片
  $dom = new DOMDocument();
  libxml_use_internal_errors(true);
  $dom->loadHTML($content);
  libxml_clear_errors();
  $xpath = new DOMXPath($dom);
  $i = 0;
  while ($imgNode = $xpath->query('//img')->item($i)) {
    $src = $imgNode->getAttribute('src');
    array_push($imgs, $src);
    ++$i;
  }
  return $imgs;
}
/**
 * 获取文章第一张图片
 * */
function get_content_img($log_cover, $content)
{
  if ($log_cover) return $log_cover;

  $imgs = get_log_image($content);
  if (count($imgs) == 0) return '';
  return $imgs[0];
}
/***
 * 分享 图片
 * */
function seoImages($content)
{
  $imgs = get_log_image($content);
  if (count($imgs) == 0) return roundImage();
  return $imgs[0];
}



/**
 * @description: 生成markdown主题样式link元素
 * @param {*} $that
 * @Date: 2023-12-22 23:13:27
 * @Author: mulingyuer
 */
function getMarkdownTheme()
{
  global $defaultMarkdownThemeHighlightMap;

  $highlightTheme = _g('pre_theme');
  // 文章主题
  $articleTheme = _g('md_theme');

  // 代码高亮主题


  if (empty($highlightTheme)) {
    // 如果文章主题对应的代码高亮主题不存在
    // 则使用默认代码高亮主题
    if (array_key_exists($articleTheme, $defaultMarkdownThemeHighlightMap)) {
      $highlightTheme = $defaultMarkdownThemeHighlightMap[$articleTheme];
    } else {
      $highlightTheme = 'juejin';
    }
  }

  // 文章主题链接
  $articleHref = TEMPLATE_URL . 'static/css/markdown/' . $articleTheme . '.css';
  $articleLink = '<link href="' . $articleHref . '" rel="stylesheet">';
  // 代码高亮主题链接
  $highlightHref = TEMPLATE_URL . 'static/css/highlight/' . $highlightTheme . '.css';
  $highlightLink = '<link href="' . $highlightHref . '" rel="stylesheet">';

  echo $articleLink . $highlightLink;
}



/**
 * 分页函数
 *
 * @param int $count 条目总数
 * @param int $perlogs 每页显示条数目
 * @param int $page 当前页码
 * @param string $url 页码的地址
 */
function sheli_fy($count, $perlogs, $page, $url, $anchor = '')
{
  $pnums = @ceil($count / $perlogs);
  $page = @min($pnums, $page);
  $prepg = $page - 1;
  $nextpg = ($page == $pnums ? 0 : $page + 1);
  $urlHome = preg_replace("|[\?&/][^\./\?&=]*page[=/\-]|", "", $url);
  $re = "";
  if ($pnums <= 1) return false;
  if ($page != 1) $re .= " <li><a href=\"$urlHome$anchor\">首页</a></li> ";
  if ($prepg) $re .= " <li class='prev'><a href=\"$url$prepg$anchor\" title=\"上一页\"><i class='iconfont icon-jiantouzuo'></i></a></li> ";
  for ($i = $page - 1; $i <= $page + 1 && $i <= $pnums; $i++) {
    if ($i > 0) {
      if ($i == $page) {
        $re .= " <li class='current'><a href='javascript:;'>$i</a></li> ";
      } elseif ($i == 1) {
        $re .= " <li><a href=\"$urlHome$anchor\">$i</a></li> ";
      } else {
        $re .= " <li><a href=\"$url$i$anchor\">$i</a></li> ";
      }
    }
  }
  if ($nextpg) $re .= " <li class='next'><a href=\"$url$nextpg$anchor\" class='nextpages' title=\"下一页\"><i class='iconfont icon-jiantouyou'></i></a></li> ";
  if ($page != $pnums) $re .= " <li class='next'><a href=\"$url$pnums$anchor\" title=\"尾页\">尾页</a></li>";
  return $re;
}

/**
 * @description: 给文章内容标题添加锚点
 * @param {*} $content 文章内容
 * @Date: 2023-03-23 20:43:02
 * @Author: mulingyuer
 */
function addAnchorPoint($content)
{
  global $catalog;
  global $catalog_count;
  $catalog = [];
  $catalog_count = 0;
  $content = preg_replace_callback('/<h([1-6])(.*?)>(.*?)<\/h\1>/i', function ($content) {
    global $catalog;
    global $catalog_count;
    $catalog_count++;
    $catalog[] = array('text' => trim(strip_tags($content[3])), 'depth' => $content[1], 'count' => $catalog_count);
    return '<h' . $content[1] . $content[2] . ' id="heading-' . $catalog_count . '">' . $content[3] . '</h' . $content[1] . '>';
  }, $content);
  return $content;
}

/**
 * @description: 获取文章目录树
 * @Date: 2023-03-23 20:36:47
 * @Author: mulingyuer
 */
function getDirectoryTree()
{
  global $catalog;
  $index = '';
  if ($catalog) {
    $index = '<ul class="directory-tree-list">' . "\n";
    $prev_depth = '';
    $to_depth = 0;
    foreach ($catalog as $catalog_item) {
      $catalog_depth = $catalog_item['depth'];
      if ($prev_depth) {
        if ($catalog_depth == $prev_depth) {
          $index .= '' . "\n";
        } elseif ($catalog_depth > $prev_depth) {
          $to_depth++;
          $index .= '<ul class="directory-tree-sub-list">' . "\n";
        } else {
          $to_depth2 = ($to_depth > ($prev_depth - $catalog_depth)) ? ($prev_depth - $catalog_depth) : $to_depth;
          if ($to_depth2) {
            for ($i = 0; $i < $to_depth2; $i++) {
              $index .= '' . "\n" . '</ul>' . "\n";
              $to_depth--;
            }
          }
          $index .= '';
        }
      }
      $index .= '<li class="directory-tree-list-item"><div class="directory-tree-list-item-container"><a class="directory-tree-list-item-link" href="#heading-' . $catalog_item['count'] . '" data-scroll="#heading-' . $catalog_item['count'] . '" title="' . $catalog_item['text'] . '"><i class="jj-icon jj-icon-send directory-tree-list-item-icon"></i>' . $catalog_item['text'] . '</a></div>';
      $prev_depth = $catalog_item['depth'];
    }
    for ($i = 0; $i <= $to_depth; $i++) {
      $index .= '' . "\n" . '</li></ul>' . "\n";
    }
    // $index = '<div id="toc-container">'."\n".'<div id="toc">'."\n".'<strong>文章目录</strong>'."\n".$index.'</div>'."\n".'</div>'."\n";
  }
  if (!$index) {
    echo '<ul class="directory-tree-list"><div class="directory-tree-list-empty">暂无目录</div></ul>';
  } else {
    echo $index;
  }
}

/**
 * @description: 获取目录树
 * @param {*} $maxDirectory 最大层级
 * @Date: 2023-06-03 22:30:49
 * @Author: mulingyuer
 */
function getJJDirectoryTree($maxDirectory = 3)
{
  global $catalog;
  $treeList = generateTreeList(array_replace_recursive(array(), $catalog));
  echo generateTreeTemplate($treeList, $maxDirectory);
}

/**
 * @description: 将扁平化目录树数组转成结构化目录树数组
 * @param {*} $list 目录树数组
 * @param {*} $depth  最大层级
 * @Date: 2023-06-03 15:42:21
 * @Author: mulingyuer
 */
function generateTreeList($list, $depth = 6)
{
  if (count($list) <= 0 || $depth <= 1) {
    return $list;
  }

  for ($i = count($list) - 1; $i >= 0; $i--) {
    $item = $list[$i];
    if ($item['depth'] == $depth) {
      $parentIndex = $i - 1;
      while ($parentIndex >= 0) {
        $parent = &$list[$parentIndex];
        if ($parent['depth'] < $depth) {
          break;
        }
        $parentIndex--;
      }

      if ($parentIndex < 0) {
        break;
      }

      if (!isset($parent['children'])) {
        $parent['children'] = array();
      }

      array_unshift($parent['children'], $item);
      array_splice($list, $i, 1);
    }
  }

  $list = array_values($list);
  return generateTreeList($list, $depth - 1);
}

/**
 * @description: 删除目录树数组指定层级children
 * @param {*} $list 目录树数组
 * @param {*} $depth  最大层级
 * @param {*} $currentDepth 当前层级
 * @Date: 2023-06-03 15:49:03
 * @Author: mulingyuer
 */
function removeChildren($list, $depth, $currentDepth = 0)
{
  foreach ($list as &$item) {
    if (isset($item['children']) && count($item['children']) > 0) {
      if ($currentDepth < $depth - 1) {
        $item['children'] = removeChildren($item['children'], $depth, $currentDepth + 1);
      } else {
        unset($item['children']);
      }
    }
  }
  return $list;
}

/**
 * @description: 生成目录树html
 * @param {*} $arr 目录树数组
 * @param {*} $depth  最大层级
 * @param {*} $currentDepth 当前层级
 * @param {*} $isChildren 是否是子级
 * @Date: 2023-06-03 16:48:54
 * @Author: mulingyuer
 */
function generateTreeTemplate($arr, $depth, $currentDepth = 1, $isChildren = false)
{
  if (count($arr) <= 0) {
    return '<div class="directory-tree-list-empty">暂无目录</div>';
  }
  if ($currentDepth > $depth) {
    return '';
  }
  $output = !$isChildren ? '<ul class="directory-tree-list">' : '';
  foreach ($arr as $item) {
    $output .= '<li class="directory-tree-list-item depth-' . $currentDepth . '"><div class="directory-tree-list-item-link-wrapper"><a class="directory-tree-list-item-link" href="#heading-' . $item['count'] . '" title="' . $item['text'] . '">' . $item['text'] . '</a></div>';
    if (!empty($item['children']) && $currentDepth < $depth) {
      $output .= '<ul class="directory-tree-sub-list">';
      $output .= generateTreeTemplate($item['children'], $depth, $currentDepth + 1, true);
      $output .= '</ul>';
    }
    $output .= '</li>';
  }
  $output .= !$isChildren ? '</ul>' : '';
  return $output;
}
